<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <select name="省" id="province">
    <!-- <option value="123">山东省</option> -->
  </select>
  <select name="市" id="city"></select>
  <select name="县" id="county"></select>
</body>
</html>
<script src="./address.js"></script>
<script>
  const provinceSelect = document.querySelector("#province");
  const citySelect = document.querySelector("#city");
  const countySelect = document.querySelector("#county");


  const data = [];
//拿取省的数据
  address.forEach(e => {
    if(e["TopID"]==0){
      data.push(e);
    }
  })
//拿取市的数据
  data.forEach(province=>{
      province.child = [];
      address.forEach(city=>{
        if(city["TopID"]==province["ID"]){ 
          province.child.push(city); 
          // //拿取区的数据  ->  可以这样简写，不过后面关于区的代码要大改
          // city.child = [];
          // address.forEach(county=>{
          //   if(city["TopID"] === county["ID"]){
          //     city.child.push(county);
          //   }
          // })
          
        }
      })
//拿取区的数据
      province.child.forEach(city=>{
        city.child = []
        address.forEach(e=>{
          if(e["TopID"]==city["ID"]){ 
            city.child.push(e);  
          }
        })
      })
  })
console.log(data);


//数据渲染
    //渲染省和默认数据
      data.forEach(province=>{
        provinceSelect.innerHTML += `<option value="${province["ID"]}">${province["AddName"]}</option>`;        
      })
      data[0].child.forEach(city=>{
          citySelect.innerHTML += `<option value="${city["ID"]}">${city["AddName"]}</option>`;
      })  
      data[0].child[0].child.forEach(county=>{
          countySelect.innerHTML += `<option value="${county["ID"]}">${county["AddName"]}</option>`;

      }) 



      //渲染市
      provinceSelect.addEventListener("change",province=>{
        citySelect.innerHTML = "";
        const city = data[province.target.value-1].child;
        city.forEach((e)=>{
          citySelect.innerHTML += `<option value="${e["ID"]}">${e["AddName"]}</option>` ;
        })
            // 区跟随相应
                countySelect.innerHTML = "";
                const county = data[province.target.value-1].child[0].child
                county.forEach((e)=>{
                    countySelect.innerHTML += `<option value="${e["ID"]}">${e["AddName"]}</option>` ;
                })  
      })


      //渲染区
          citySelect.addEventListener("change",citynum=>{
            countySelect.innerHTML = "";
            const county = address[citynum.target.value-1].child;
            county.forEach((e)=>{
                countySelect.innerHTML += `<option value="${e["ID"]}">${e["AddName"]}</option>` ;
            }) 
          })
 
</script>